package com.longe.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelTest002 {

    public static void main(String[] args) throws Exception {
        //定义一个文件输入流
        FileInputStream fis = new FileInputStream("demo1.txt");
        //获取channel
        FileChannel fileChannelIn = fis.getChannel();

        //定义一个文件输出流
        FileOutputStream fos = new FileOutputStream("demo2.txt");
        //获取channel
        FileChannel fileChannelOut = fos.getChannel();

        //定义一个Buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(128);

        while (true) {
            //复位
            byteBuffer.clear();
            //从channel读取到buffer
            int read = fileChannelIn.read(byteBuffer);
            if(read == -1) {
                break;
            }
            //翻转
            byteBuffer.flip();
            //从buffer写入到channel
            fileChannelOut.write(byteBuffer);
        }

        //关闭通道和流
        fileChannelIn.close();
        fis.close();
        fileChannelOut.close();
        fos.close();
    }
}
